﻿using AutoMapper;
using MediatR;
using RBAC_Uthorization.API.Application.Command.RoleCommand;
using RBAC_Uthorization.API.DTO;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Domain.Entity;
using RBAC_Uthorization.Infrstructre.Interface;

namespace RBAC_Uthorization.API.Application.CommandHandlers.RoleHandler
{
    public class RoleUpdateCommandHandlers : IRequestHandler<RoleUpdateCommand, ApiResult<int>>
    {
        private readonly IRoleRepository _roleRepository;
        private readonly ILogger<RoleUpdateCommandHandlers> _logger;


        public RoleUpdateCommandHandlers(IRoleRepository roleRepository, ILogger<RoleUpdateCommandHandlers> logger)
        {
            _roleRepository = roleRepository;
            _logger = logger;
        }

        public async Task<ApiResult<int>> Handle(RoleUpdateCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var data = await _roleRepository.GetbyIdAsync(request.dto.id);
                if (data == null)
                {
                    return new ApiResult<int>
                    {
                        Code = ResultCode.Fail,
                        Message = "角色信息不存在"
                    };
                }
                data.name = request.dto.name;
                data.role_type = request.dto.role_type;
                data.data_scope = request.dto.data_scope;
                data.role_level = request.dto.role_level;
                data.useable = request.dto.useable;
                data.update_date = DateTime.UtcNow;
                data.update_by = request.updateName;

                var result = await _roleRepository.UpdateAsync(data);
                _logger.LogInformation($"修改人：{request.updateName}更新角色信息成功:{request.dto.id}");
                return new ApiResult<int>();
            }
            catch (Exception e)
            {
                _logger.LogError($"更新角色信息失败:{e.Message}->{e.StackTrace}->{e.InnerException}");
                return new ApiResult<int>
                {
                    Code = ResultCode.Fail,
                    Message = "更新角色信息失败"
                };
            }
        }
    }
}
